﻿using ShiQuan.DataRepository;
using ShiQuan.IotDevice.Entity;
using ShiQuan.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ShiQuan.IotDevice.Business
{
    /// <summary>
    /// 设备数量
    /// </summary>
    public class IotDeviceDataBLL : BasicIotDeviceBLL<IotDeviceDataEntity>
    {
        /// <summary>
        /// 保存设备数据
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public bool SaveData(string jsonData)
        {
            var source = jsonData.ToJObject();
            if (source["serialnumber"].IsEmpty())
                throw new Exception("设备标识不能为空！");
            var serialNumber = source["serialnumber"].ToString();

            var iotDeviceInstall = new IotDeviceInstallBLL().FindEntity(my => my.SerialNumber == serialNumber);
            if (iotDeviceInstall == null)
            {
                throw new Exception("未能找到设备安装信息！");
            }
            List<IotDeviceSensorEntity> deviceSensors = new IotDeviceSensorBLL().GetList(my => my.RefDeviceId == iotDeviceInstall.RefDeviceId).OrderBy(my => my.Code).ToList();
            if (deviceSensors == null || deviceSensors.Count <= 0)
            {
               throw new Exception("未能找到设备单位系数信息！");
            }
            DateTime time = DateTime.Now;
            if (source["datetime"].IsEmpty() == false)
                DateTime.TryParse(source["datetime"].ToString(), out time);
            int index = 0;
            if (source["index"].IsEmpty() == false)
                int.TryParse(source["index"].ToString(), out index);

            IRepository db = new RepositoryFactory().BaseRepository(dbContext).BeginTrans();
            try
            {
                IotDeviceLastEntity deviceLast = db.FindEntity<IotDeviceLastEntity>(my=>my.Id == iotDeviceInstall.Id);
                if (deviceLast == null)
                    deviceLast = new IotDeviceLastEntity();
                /*2019-12-09 侯连文 初始、清除设备最新数据*/
                deviceLast.OC01Text = string.Empty;
                deviceLast.OC01Value = null;
                deviceLast.OC02Text = string.Empty;
                deviceLast.OC02Value = null;
                deviceLast.Humidity01Text = string.Empty;
                deviceLast.Humidity01Value = null;
                deviceLast.Humidity02Text = string.Empty;
                deviceLast.Humidity02Value = null;

                /*删除已存在数据*/
                db.Delete<IotDeviceDataEntity>(my => my.SerialNumber == serialNumber && my.Index == index);
                for (int i = 0; i < deviceSensors.Count; i++)
                {
                    IotDeviceSensorEntity item = deviceSensors[i];
                    if (source["data" + Convert.ToInt32(item.Code).ToString("00")].IsEmpty())
                        continue;
                    
                    string value = source["data" + Convert.ToInt32(item.Code).ToString("00")].ToString();
                    switch (item.Name)
                    {
                        case "温度":
                            {
                                if (string.IsNullOrEmpty(deviceLast.OC01Text))
                                {
                                    if (item.Factor != null)
                                        deviceLast.OC01Value = Convert.ToInt32(value) * item.Factor.Value;
                                    else
                                        deviceLast.OC01Value = Convert.ToInt32(value);
                                    deviceLast.OC01Text = deviceLast.OC01Value.ToString() + item.Unit;
                                }
                                else
                                {
                                    if (item.Factor != null)
                                        deviceLast.OC02Value = Convert.ToInt32(value) * item.Factor.Value;
                                    else
                                        deviceLast.OC02Value = Convert.ToInt32(value);
                                    deviceLast.OC02Text = deviceLast.OC02Value.ToString() + item.Unit;
                                }
                                break;
                            }
                        case "湿度":
                            {
                                if (string.IsNullOrEmpty(deviceLast.Humidity01Text))
                                {
                                    if (item.Factor != null)
                                        deviceLast.Humidity01Value = Convert.ToInt32(value) * item.Factor.Value;
                                    else
                                        deviceLast.Humidity01Value = Convert.ToInt32(value);

                                    deviceLast.Humidity01Text = deviceLast.Humidity01Value.ToString() + item.Unit;
                                }
                                else
                                {
                                    if (item.Factor != null)
                                        deviceLast.Humidity02Value = Convert.ToInt32(value) * item.Factor.Value;
                                    else
                                        deviceLast.Humidity02Value = Convert.ToInt32(value);
                                    deviceLast.Humidity02Text = deviceLast.Humidity02Value.ToString() + item.Unit;
                                }
                                break;
                            }
                    }

                    IotDeviceDataEntity entity = new IotDeviceDataEntity();
                    entity.Id = Guid.NewGuid().ToString();
                    entity.RefSersorId = item.Id;
                    entity.RefCorpId = iotDeviceInstall.RefCorpId;

                    entity.RefDeviceId = item.RefDeviceId;
                    entity.DeviceName = item.DeviceName;
                    entity.RefInstallId = iotDeviceInstall.Id;/*设备安装*/
                    entity.SerialNumber = serialNumber;
                    entity.SersorName = item.Name;
                    entity.Unit = item.Unit;

                    entity.Index = index;
                    entity.Time = time;

                    entity.Date = time.Date;
                    entity.Year = time.Year;
                    entity.Month = time.Month;
                    entity.Day = time.Day;
                    entity.Week = (int)time.DayOfWeek;
                    entity.Hour = time.Hour;
                    
                    if (item.Factor != null)
                        entity.Value = Convert.ToInt32(value) * item.Factor.Value;
                    else
                        entity.Value = Convert.ToInt32(value);
                    entity.Text = entity.Value.ToString() + item.Unit;

                    //iotDeviceDataBLL.SaveForm(string.Empty, entity);
                    db.Insert<IotDeviceDataEntity>(entity);

                    /*预警信息*/

                }
                deviceLast.SerialNumber = serialNumber;
                deviceLast.Index = index;
                deviceLast.DateTime = time;

                deviceLast.RefCorpId = iotDeviceInstall.RefCorpId;
                deviceLast.RefDeviceId = iotDeviceInstall.RefDeviceId;
                deviceLast.DeviceName = iotDeviceInstall.DeviceName;
                deviceLast.RefInstallId = iotDeviceInstall.Id;
                if (string.IsNullOrEmpty(deviceLast.Id))
                {
                    deviceLast.Id = iotDeviceInstall.Id; /*使用安装标识*/
                    db.Insert<IotDeviceLastEntity>(deviceLast);
                }
                else
                    db.Update<IotDeviceLastEntity>(deviceLast);
                db.Commit();
                return true;
            }
            catch (Exception)
            {
                db.Rollback();
                throw;
            }
            
        }
        /// <summary>
        /// 查询过滤
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        protected override Expression<Func<IotDeviceDataEntity, bool>> QueryStringToExpression(Expression<Func<IotDeviceDataEntity, bool>> expression, string queryJson)
        {
            if (string.IsNullOrEmpty(queryJson))
                return expression;
            var queryParam = queryJson.ToJObject();
            if (queryParam["RefCorpId"].IsEmpty() == false && queryParam["RefCorpId"].ToString() != "-1")
            {
                string keyword = queryParam["RefCorpId"].ToString();
                expression = expression.And(my => my.RefCorpId == keyword);
            }
            if (queryParam["RefInstallId"].IsEmpty() == false && queryParam["RefInstallId"].ToString() != "-1")
            {
                string keyword = queryParam["RefInstallId"].ToString();
                expression = expression.And(my => my.RefInstallId == keyword);
            }
            if (queryParam["RefSersorId"].IsEmpty() == false && queryParam["RefSersorId"].ToString() != "-1")
            {
                string keyword = queryParam["RefSersorId"].ToString();
                expression = expression.And(my => my.RefSersorId == keyword);
            }
            if (queryParam["SerialNumber"].IsEmpty() == false && queryParam["SerialNumber"].ToString() != "-1")
            {
                string keyword = queryParam["SerialNumber"].ToString();
                expression = expression.And(my => my.SerialNumber == keyword);
            }
            if (queryParam["SersorName"].IsEmpty() == false && queryParam["SersorName"].ToString() != "-1")
            {
                string keyword = queryParam["SersorName"].ToString();
                expression = expression.And(my => my.SersorName == keyword);
            }
            if (queryParam["StartDate"].IsEmpty() == false && queryParam["StartDate"].ToString() != "-1")
            {
                var startdate = DateTime.MinValue;
                var keyword = queryParam["StartDate"].ToString();
                DateTime.TryParse(keyword, out startdate);
                if (startdate == DateTime.MinValue)
                    startdate = DateTime.Today;
                expression = expression.And(my => my.Date >= startdate);
            }
            if (queryParam["CloseDate"].IsEmpty() == false && queryParam["CloseDate"].ToString() != "-1")
            {
                var closedate = DateTime.MinValue;
                string keyword = queryParam["CloseDate"].ToString();
                DateTime.TryParse(keyword, out closedate);
                if (closedate == DateTime.MinValue)
                    closedate = DateTime.Today;
                expression = expression.And(my => my.Date <= closedate);
            }
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                string condition = queryParam["condition"].ToString();
                string keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Index":
                        {
                            int index = -1;
                            int.TryParse(keyword, out index);
                            expression = expression.And(my => my.Index == index);
                            break;
                        }
                    default: break;
                }
            }
            return expression;
        }
    }
}
